package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {


    @Override
    public ResponseResult login(AdUserDto dto) {
        //检查参数
        if(StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户名查询用户信息
//        List<AdUser> list = list(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
//
//        //判断用名是否存在 如果为null，提示信息不存在
//    if(list==null || list.isEmpty()){
//        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
//    }
//        //如果存在，判断用户密码
//        AdUser adUser = list.get(0);
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));

        if(adUser== null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //将用户输入的密码加盐 进行md5加密 ，得到密文和数据库做对比
        //import org.springframework.util.DigestUtils;
        String password = DigestUtils.md5DigestAsHex((dto.getPassword() + adUser.getSalt()).getBytes());
        //密码一致

        if(password.equals(adUser.getPassword())){
            //生成taken 返回用户信息放入集合
            Map map=new HashMap<>();

            String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
            map.put("token",token);
            //盐和密码不能返回前端设置为空
            adUser.setSalt("");
            adUser.setPassword("");//UserVo
            map.put("user",adUser);
            return ResponseResult.okResult(map);
        }else {
            //密码不一致

            //返回密码错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
    }
}
